package com.neuedu.springmvc.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neuedu.springmvc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Controller
//@ResponseBody
@RestController   // json交互会经常性的用到 ResponseBody Controller      组合到一起 可以使用@RestController代替
public class UserController {


    /**
     * http://localhost:8080/springmvc10/req1
     *
     * @return
     */

    @RequestMapping("/req1")
    public String req1() {
        return "success";
    }


    @RequestMapping("/reqMap")
    public String reqMap() throws JsonProcessingException {


        Map user = new HashMap();
        user.put("id", 100);
        user.put("name", "jshand");
        user.put("age", 18);
        user.put("address", "黑龙江");

        ObjectMapper objectMapper = new ObjectMapper();

        //内存对象转换成 json
        String json = objectMapper.writeValueAsString(user);
        System.out.println("json = " + json);
        return json;
    }





    @RequestMapping("/reqMap2")
    public Map reqMap2() throws JsonProcessingException {


        Map map = new HashMap();
        map.put("id", 100);
        map.put("name", "jshand");
        map.put("age", 18);
        map.put("address", "黑龙江");


        return map;
    }




    @RequestMapping("/reqUser")
    public User reqUser() throws JsonProcessingException {


        //模拟从数据库中查询用户
        User user = new User(
                100,
                "admin",
                "123456",
                "管理员",
                "18888888888"
        );




        return user;
    }

    @RequestMapping("/reqUserList")
    public List<User> reqUserList() throws JsonProcessingException {


        //模拟从数据库中查询用户
        List list = new ArrayList();
        for (int i = 0; i < 10; i++) {
            User user = new User(
                    i+100,
                    i+"admin",
                    i+"123456",
                    i+"管理员",
                    i+"18888888888"
            );
            list.add(user);
        }

        return list;
    }


}
